<template>
  <div class="profile-container">
    <div class="profile-header">
      <div class="user-info">
        <el-avatar :size="80" :src="userInfo?.avatar || defaultAvatar" @click="goToSettings"></el-avatar>
        <div class="user-details">
          <h2 class="username">{{ userInfo?.nickname || userInfo?.username || '用户未找到' }}</h2>
          <div class="user-meta">
            <span v-if="userInfo?.role === 3" class="role-tag admin">管理员</span>
            <span v-else-if="userInfo?.role === 2" class="role-tag expert">专家</span>
            <span class="join-time">加入于 {{ formatDate(userInfo?.createTime) }}</span>
          </div>
          <div class="user-bio" v-if="userInfo?.bio">{{ userInfo.bio }}</div>
        </div>
      </div>
      
      <div class="user-actions" v-if="isCurrentUser">
        <el-button type="primary" @click="$router.push('/settings')">
          <i class="el-icon-setting"></i> 编辑资料
        </el-button>
      </div>
      <div class="user-actions" v-else>
        <el-button type="primary" @click="followUser" :disabled="followLoading" v-if="!isFollowing">
          <i class="el-icon-plus"></i> 关注
        </el-button>
        <el-button @click="unfollowUser" :disabled="followLoading" v-else>
          <i class="el-icon-check"></i> 已关注
        </el-button>
        <el-button @click="sendMessage">
          <i class="el-icon-message"></i> 发消息
        </el-button>
      </div>
    </div>
    
    <div class="profile-stats">
      <div class="stat-item">
        <div class="stat-value">{{ questionTotal || 0 }}</div>
        <div class="stat-label">提问</div>
      </div>
      <div class="stat-item">
        <div class="stat-value">{{ answerTotal || 0 }}</div>
        <div class="stat-label">回答</div>
      </div>
      <div class="stat-item">
        <div class="stat-value">{{ followerCount || 0 }}</div>
        <div class="stat-label">关注者</div>
      </div>
      <div class="stat-item">
        <div class="stat-value">{{ followingCount || 0 }}</div>
        <div class="stat-label">关注</div>
      </div>
    </div>
    
    <div class="profile-content">
      <el-tabs v-model="activeTab" @tab-click="handleTabChange">
        <el-tab-pane label="我的提问" name="questions">
          <div class="tab-content">
            <div v-if="loading" class="loading">
              <el-skeleton :rows="5" animated />
            </div>
            <div v-else-if="questionList.length === 0" class="empty-list">
              <el-empty description="暂无提问记录" />
            </div>
            <div v-else class="question-list">
              <div v-for="question in questionList" :key="question.id" class="question-item" @click="viewQuestion(question.id)">
                <div class="question-title">{{ question.title }}</div>
                <div class="question-meta">
                  <span class="question-stats">{{ question.answerCount }} 回答</span>
                  <span class="question-time">{{ formatDate(question.createTime) }}</span>
                </div>
              </div>
              <div class="pagination">
                <el-pagination
                  background
                  layout="prev, pager, next"
                  :total="questionTotal"
                  :page-size="pageSize"
                  :current-page="currentPage"
                  @current-change="handlePageChange"
                />
              </div>
            </div>
          </div>
        </el-tab-pane>
        
        <el-tab-pane label="我的回答" name="answers">
          <div class="tab-content">
            <div v-if="loading" class="loading">
              <el-skeleton :rows="5" animated />
            </div>
            <div v-else-if="answerList.length === 0" class="empty-list">
              <el-empty description="暂无回答记录" />
            </div>
            <div v-else class="answer-list">
              <div v-for="answer in answerList" :key="answer.id" class="answer-item" @click="viewQuestion(answer.questionId)">
                <div class="question-title">回答了：{{ answer.questionTitle }}</div>
                <div class="answer-content">{{ answer.content }}</div>
                <div class="answer-meta">
                  <span v-if="answer.isAccepted" class="accepted-tag">已采纳</span>
                  <span class="answer-time">{{ formatDate(answer.createTime) }}</span>
                </div>
              </div>
              <div class="pagination">
                <el-pagination
                  background
                  layout="prev, pager, next"
                  :total="answerTotal"
                  :page-size="pageSize"
                  :current-page="currentPage"
                  @current-change="handlePageChange"
                />
              </div>
            </div>
          </div>
        </el-tab-pane>
        
        <el-tab-pane label="我的收藏" name="collections">
          <div class="tab-content">
            <div v-if="loading" class="loading">
              <el-skeleton :rows="5" animated />
            </div>
            <div v-else-if="collectionList.length === 0" class="empty-list">
              <el-empty description="暂无收藏记录" />
            </div>
            <div v-else class="collection-list">
              <div v-for="question in collectionList" :key="question.id" class="question-item" @click="viewQuestion(question.id)">
                <div class="question-title">{{ question.title }}</div>
                <div class="question-meta">
                  <span class="question-stats">{{ question.answerCount }} 回答</span>
                  <span class="question-time">{{ formatDate(question.createTime) }}</span>
                </div>
              </div>
              <div class="pagination">
                <el-pagination
                  background
                  layout="prev, pager, next"
                  :total="collectionTotal"
                  :page-size="pageSize"
                  :current-page="currentPage"
                  @current-change="handlePageChange"
                />
              </div>
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed, watch } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import { getUserQuestions, getUserAnswers, getUserInfo } from '../api/user';
import { getCollectedQuestions } from '../api/collection';
import { useUserStore } from '../stores/user';

const route = useRoute();
const router = useRouter();
const userStore = useUserStore();

// 默认头像 - 使用Base64编码的简单默认头像
const defaultAvatar = '';

// 状态数据
const userInfo = ref(null);
const questionList = ref([]);
const answerList = ref([]);
const collectionList = ref([]);
const loading = ref(false);
const activeTab = ref('questions');
const currentPage = ref(1);
const pageSize = ref(10);
const questionTotal = ref(0);
const answerTotal = ref(0);
const collectionTotal = ref(0);

// 关注相关数据
const isFollowing = ref(false);
const followLoading = ref(false);
const followerCount = ref(0);
const followingCount = ref(0);

// 判断是否是当前登录用户
const isCurrentUser = computed(() => {
  if (!userStore.isLogin || !userInfo.value || !userStore.userInfo) return false;
  return userInfo.value.id === userStore.userInfo.id;
});

// 加载用户信息
const loadUserInfo = async () => {
  try {
    const userId = route.params.id;
    if (!userId) return;
    
    const res = await getUserInfo(userId);
    if (res.code === 200) {
      userInfo.value = res.data;
      
      // 如果有关注相关的接口，这里可以获取关注状态和数量
      // 这里仅做示例，需要根据实际接口调整
      followerCount.value = userInfo.value.followerCount || 0;
      followingCount.value = userInfo.value.followingCount || 0;
      isFollowing.value = userInfo.value.isFollowing || false;
    } else {
      ElMessage.error(res.message || '获取用户信息失败');
    }
  } catch (error) {
    console.error('获取用户信息失败:', error);
    ElMessage.error('获取用户信息失败');
  }
};

// 关注用户
const followUser = async () => {
  if (!userStore.isLogin) {
    ElMessage.warning('请先登录');
    router.push('/login');
    return;
  }
  
  try {
    followLoading.value = true;
    // 这里调用关注用户API
    // await followUserApi(userInfo.value.id);
    
    isFollowing.value = true;
    followerCount.value++;
    ElMessage.success('关注成功');
  } catch (error) {
    console.error('关注用户失败:', error);
    ElMessage.error('关注失败');
  } finally {
    followLoading.value = false;
  }
};

// 取消关注
const unfollowUser = async () => {
  try {
    followLoading.value = true;
    // 这里调用取消关注API
    // await unfollowUserApi(userInfo.value.id);
    
    isFollowing.value = false;
    followerCount.value = Math.max(0, followerCount.value - 1);
    ElMessage.success('已取消关注');
  } catch (error) {
    console.error('取消关注失败:', error);
    ElMessage.error('取消关注失败');
  } finally {
    followLoading.value = false;
  }
};

// 发送私信
const sendMessage = () => {
  if (!userStore.isLogin) {
    ElMessage.warning('请先登录');
    router.push('/login');
    return;
  }
  
  ElMessage.info('发送私信功能开发中');
};

// 加载用户提问
const loadUserQuestions = async () => {
  try {
    loading.value = true;
    const userId = route.params.id;
    const res = await getUserQuestions(userId, {
      current: currentPage.value,
      size: pageSize.value
    });
    if (res.code === 200) {
      questionList.value = res.data.records || [];
      questionTotal.value = res.data.total || 0;
    } else {
      ElMessage.error(res.message || '获取用户提问失败');
    }
  } catch (error) {
    console.error('获取用户提问失败:', error);
    ElMessage.error('获取用户提问失败');
  } finally {
    loading.value = false;
  }
};

// 加载用户回答
const loadUserAnswers = async () => {
  try {
    loading.value = true;
    const userId = route.params.id;
    const res = await getUserAnswers(userId, {
      current: currentPage.value,
      size: pageSize.value
    });
    if (res.code === 200) {
      answerList.value = res.data.records || [];
      answerTotal.value = res.data.total || 0;
    } else {
      ElMessage.error(res.message || '获取用户回答失败');
    }
  } catch (error) {
    console.error('获取用户回答失败:', error);
    ElMessage.error('获取用户回答失败');
  } finally {
    loading.value = false;
  }
};

// 加载用户收藏
const loadUserCollections = async () => {
  try {
    loading.value = true;
    const res = await getCollectedQuestions({
      current: currentPage.value,
      size: pageSize.value
    });
    if (res.code === 200) {
      collectionList.value = res.data.records || [];
      collectionTotal.value = res.data.total || 0;
    } else {
      ElMessage.error(res.message || '获取用户收藏失败');
    }
  } catch (error) {
    console.error('获取用户收藏失败:', error);
    ElMessage.error('获取用户收藏失败');
  } finally {
    loading.value = false;
  }
};

// 切换标签页
const handleTabChange = (tab) => {
  currentPage.value = 1;
  activeTab.value = tab.props.name;
  loadTabData();
};

// 切换页码
const handlePageChange = (page) => {
  currentPage.value = page;
  loadTabData();
};

// 根据当前标签页加载数据
const loadTabData = () => {
  switch (activeTab.value) {
    case 'questions':
      loadUserQuestions();
      break;
    case 'answers':
      loadUserAnswers();
      break;
    case 'collections':
      loadUserCollections();
      break;
  }
};

// 查看问题详情
const viewQuestion = (id) => {
  router.push(`/questions/${id}`);
};

// 格式化日期
const formatDate = (date) => {
  if (!date) return '';
  const d = new Date(date);
  return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`;
};

// 跳转到设置页面
const goToSettings = () => {
  if (isCurrentUser.value) {
    router.push('/settings');
  }
};

// 监听路由参数变化，当用户ID变化时重新加载用户信息
watch(() => route.params.id, (newId, oldId) => {
  if (newId && newId !== oldId) {
    loadUserInfo();
    currentPage.value = 1;
    loadTabData();
  }
});

onMounted(() => {
  loadUserInfo();
  loadTabData();
});
</script>

<style scoped>
.profile-container {
  max-width: 1000px;
  margin: 0 auto;
  padding: 20px;
}

.profile-header {
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  padding: 24px;
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
}

.user-info {
  display: flex;
  align-items: flex-start;
}

.user-details {
  margin-left: 20px;
}

.username {
  margin: 0 0 10px;
  font-size: 24px;
  color: #333;
}

.user-meta {
  display: flex;
  align-items: center;
  gap: 10px;
  color: #666;
  margin-bottom: 8px;
}

.user-bio {
  color: #666;
  font-size: 14px;
  line-height: 1.6;
  margin-top: 10px;
  max-width: 500px;
}

.role-tag {
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 12px;
  color: #fff;
}

.role-tag.admin {
  background-color: #f56c6c;
}

.role-tag.expert {
  background-color: #e6a23c;
}

.profile-stats {
  display: flex;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
  padding: 16px;
}

.stat-item {
  flex: 1;
  text-align: center;
  padding: 0 10px;
  border-right: 1px solid #eee;
}

.stat-item:last-child {
  border-right: none;
}

.stat-value {
  font-size: 24px;
  font-weight: 600;
  color: #409EFF;
}

.stat-label {
  font-size: 14px;
  color: #888;
  margin-top: 4px;
}

.profile-content {
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  padding: 20px;
}

.tab-content {
  padding: 10px 0;
}

.loading {
  padding: 20px 0;
}

.question-item, .answer-item {
  padding: 15px 0;
  border-bottom: 1px solid #eee;
  cursor: pointer;
}

.question-item:hover, .answer-item:hover {
  background-color: #f9f9f9;
}

.question-title {
  font-size: 16px;
  font-weight: 500;
  margin-bottom: 8px;
  color: #333;
}

.question-meta, .answer-meta {
  display: flex;
  justify-content: space-between;
  font-size: 12px;
  color: #999;
}

.answer-content {
  font-size: 14px;
  color: #666;
  margin: 8px 0;
  line-height: 1.5;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.accepted-tag {
  color: #67c23a;
  font-weight: 500;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.el-avatar {
  cursor: pointer;
}
</style> 